#include "stdafx.h"

const glm::vec3 Line::COLOR_T(0, 1, 0);
const glm::vec3 Line::COLOR_F(1, 0, 0);

Line::Line(Dot * dot1, Dot * dot2)
{
	d1 = dot1;
	d2 = dot2;

	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
}

Line::~Line()
{
}

bool Line::render()
{
	int x1 = d1->getX();
	int y1 = d1->getY();
	int x2 = d2->getX();
	int y2 = d2->getY();

	float verts[] = {
		x1, y1,
		x2, y2,
	};

	Program * prog = ProgramMgr::getInstance()->get("pure");
	prog->use();
	prog->uniform3f("color", color);

	glm::mat4 model(1.0f);
	prog->uniformmat4("model", model);

	glBindVertexArray(VAO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);
	glEnableVertexAttribArray(0);
	glDrawArrays(GL_LINES, 0, 2);

	return true;
}

void Line::setColor(const glm::vec3 & color)
{
	this->color = color;
}

bool Line::intersect(Line * line)
{
	Dot * d3 = line->getEnd1();
	Dot * d4 = line->getEnd2();

	int c1 = cross(d1->getX(), d1->getY(), d2->getX(), d2->getY(), d3->getX(), d3->getY());
	int c2 = cross(d1->getX(), d1->getY(), d2->getX(), d2->getY(), d4->getX(), d4->getY());
	int c3 = cross(d3->getX(), d3->getY(), d4->getX(), d4->getY(), d1->getX(), d1->getY());
	int c4 = cross(d3->getX(), d3->getY(), d4->getX(), d4->getY(), d2->getX(), d2->getY());

	return (c1 < 0 && c2 > 0 || c1 > 0 && c2 < 0) && (c3 < 0 && c4 > 0 || c3 > 0 && c4 < 0);
}

int Line::cross(int x1, int y1, int x2, int y2, int x3, int y3)
{
	return (x2 - x1)*(y3 - y1) - (x3 - x1)*(y2 - y1);
}